package com.hdcircles.autoform.component;

import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Build;

import com.hdcircles.autoform.app.App;
import com.hdcircles.autoform.util.LogUtil;
import com.hdcircles.autoform.util.ToastUtil;

import java.io.PrintWriter;
import java.io.StringWriter;
import java.io.Writer;

/**
 * Created by hdcircles on 2016/9/21.
 */

public class CrashHandler implements Thread.UncaughtExceptionHandler {

    private static Thread.UncaughtExceptionHandler defaultHandler=null;

    private Context context=null;

    private final String TAG=CrashHandler.class.getSimpleName();

    public CrashHandler(Context context){
        this.context=context;
    }

    /**
     *初始化，设置该Crash Handler为程序的默认处理器
     */
    public static void init(CrashHandler crashHandler){
        defaultHandler=Thread.getDefaultUncaughtExceptionHandler();
        Thread.setDefaultUncaughtExceptionHandler(crashHandler);
    }
    @Override
    public void uncaughtException(Thread thread, Throwable throwable) {
        System.out.println(throwable.toString());
        LogUtil.e(TAG,throwable.toString());
        LogUtil.e(TAG,collectCrashDeviceInfo());
        LogUtil.e(TAG,getCrashInfo(throwable));
        //调用系统错误信息
        defaultHandler.uncaughtException(thread,throwable);
        ToastUtil.shortShow("抱歉,程序发生异常即将退出");
        App.getInstance().exitApp();
    }


    /**
     *
     * @return  收集程序崩溃的详细信息
     */
    public String getCrashInfo(Throwable throwable){
        Writer result=new StringWriter();
        PrintWriter printWriter=new PrintWriter(result);
        throwable.setStackTrace(throwable.getStackTrace());
        throwable.printStackTrace(printWriter);
        return result.toString();
    }

    /**
     *
     * @return 收集程序崩溃的设备信息
     */
    public String collectCrashDeviceInfo(){
        try {
            PackageManager pm=context.getPackageManager();
            PackageInfo pi=pm.getPackageInfo(context.getPackageName(),PackageManager.GET_ACTIVITIES);
            String versionName=pi.versionName;
            String model= Build.MODEL;
            String androidVersion= Build.VERSION.RELEASE;
            String manufacturer=Build.MANUFACTURER;
            return versionName+"  "+model+"  "+androidVersion+"  "+manufacturer;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return null;
    }
}
